import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
import { Router } from '@angular/router';
import { Observable } from 'rxjs';
import { AuthorityService } from './authority.service';

import 'rxjs/add/operator/timeout';
@Injectable({
    providedIn: 'root'
})
export class HttpService {

    constructor(private httpClient: HttpClient, private router: Router, private authorityService: AuthorityService) { }

    public getCookie(sName: string) {
        const aCookie = document.cookie.split('; ');
        for (let i = 0; i < aCookie.length; i++) {
            const aCrumb = aCookie[i].split('=');
            if (sName === aCrumb[0]) {
                return (aCrumb[1]);
            }
        }
    }

    private request(method, url, params: any, body: any, timeout?: number) {
        // 经常，我们在路由前面省略 / ，这里统一加上
        if (url.startsWith('bsa_')) {
            url = '/' + url;
        }
        const cookie = this.getCookie('csrftoken');
        const csrftoken = cookie ? { 'X-CSRFToken': cookie } : {};
        if (method === 'POST_FORM') {
            method = 'POST';
            csrftoken['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
        }
        const headers = new HttpHeaders(csrftoken);

        timeout = 30 * 60 * 1000;
        const options = {
            body,
            params,
            headers
        };
        return this.httpClient.request(method, url, options)
            .timeout(timeout).catch((error: Response | any) => {
                const codeStatus = error.status;
                const authCode = error.code;
                // 权限状态码判断
                this.authorityService.pureAuthority(codeStatus, authCode);
                return Observable.throw(error);
            });
    }

    get(url: string, params?: any, timeout?: number): Observable<any> {
        return this.request('GET', url, params, {}, timeout);
    }

    post(url: string, params?: any, body?: any, timeout?: number): Observable<any> {
        return this.request('POST', url, params, body, timeout);
    }

    postForm(url: string, params?: any, body?: any, timeout?: number): Observable<any> {
        return this.request('POST_FORM', url, params, body, timeout);
    }

    put(url: string, params?: any, body?: any, timeout?: number): Observable<any> {
        return this.request('PUT', url, params, body, timeout);
    }

    delete(url: string, params?: any, body?: any, timeout?: number): Observable<any> {
        return this.request('DELETE', url, params, body, timeout);
    }

}


